/**
 * @Project Name:authentication-server
 * @Package Name:cn.hoofungson.blog.authentication.server.service
 * @Since JDK 1.8
 */

package cn.hoofungson.blog.authentication.server.config.security.service;

import cn.hoofungson.blog.authentication.server.client.user.UserFeignClient;
import cn.hoofungson.blog.business.service.interfaces.domain.dto.user.UserDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * @Description: CustomUserDetailsService
 * @Author 胡松 hoofungson@163.com
 * @Date 2020-01-16 17:41
 * @Version V1.0
 */
@Service
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private UserFeignClient userFeignClient;

    /**
     * Locates the user based on the username. In the actual implementation, the search
     * may possibly be case sensitive, or case insensitive depending on how the
     * implementation instance is configured. In this case, the <code>UserDetails</code>
     * object that comes back may have a username that is of a different case than what
     * was actually requested..
     *
     * @param username the username identifying the user whose data is required.
     * @return a fully populated user record (never <code>null</code>)
     * @throws UsernameNotFoundException if the user could not be found or the user has no
     *                                   GrantedAuthority
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        ResponseEntity<UserDTO> responseEntity = this.userFeignClient.getByUsername(username);
        if (null == responseEntity || null == responseEntity.getBody()) {
            throw new UsernameNotFoundException("用户" + username + "不存在！！");
        }
        UserDTO userDTO = responseEntity.getBody();
//        String password = passwordEncoder.encode("cpCTuk8q07^RzANM");
        return new User(userDTO.getUsername(), userDTO.getPassword(), userDTO.getEnabled(), userDTO.getAccountNonExpired(), userDTO.getCredentialsNonExpired(), userDTO.getAccountNonLocked(), AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_STILL_API_ADMIN"));
    }
}
